package service_blog_mirchen_com

import (
	"github.com/jinzhu/gorm"
	"gen-go/BlogServices"
)

//service结构
type TagServiceHandler struct {
	orm *gorm.DB
}

//tag
type Tags struct {
	Id        int64  `gorm:"primary_key"`
	TagName   string
	Recommend int64
}

type ArticleTag struct {
	Id        int64
	ArticleId int64
	TagId     int64
}

func NewTagServiceHandler(getOrm *gorm.DB) *TagServiceHandler {
	return &TagServiceHandler{orm:getOrm}
}

func (tsh *TagServiceHandler) GetAllTags() ([]*BlogServices.Tag, error) {
	tags := []Tags{}
	retags := []*BlogServices.Tag{}
	err := tsh.orm.Find(&tags).Error
	if err != nil {
		return retags, err
	} else {
		if len(tags) > 0 {
			for _, v := range tags {
				retags = append(retags, &BlogServices.Tag{
					ID:v.Id,
					TagName:v.TagName,
					Recommend:v.Recommend,
				})
			}
		}
		return retags, nil
	}
}

func (tsh *TagServiceHandler) GetTagsByArticleId(articleid int64) ([]*BlogServices.Tag, error) {
	article_tags := []ArticleTag{}
	retags := []*BlogServices.Tag{}
	err := tsh.orm.Where("article_id=?", articleid).Find(&article_tags).Error
	if err != nil {
		return retags, err
	} else {
		length := len(article_tags)
		if length > 0 {
			tagids := make([]int64,length)
			for k, v := range article_tags {
				tagids[k] = v.TagId
			}
			tags := []Tags{}
			err = tsh.orm.Where(tagids).Find(&tags).Error
			if err != nil {
				return retags, err
			}
			if len(tags) > 0 {
				for _, v := range tags {
					retags = append(retags, &BlogServices.Tag{
						ID:v.Id,
						TagName:v.TagName,
						Recommend:v.Recommend,
					})
				}
			}
		}
		return retags, nil
	}
}
